const { sqlPromise } = require("../db/sqlPromise");

exports.getArticleCates = async (req, res) => {
  const sql = "select * from ev_article_cate";
  let results = await sqlPromise(sql);
  if (!results.length)
    return res.send({ status: 1, msg: "获取文章分类列表失败" });
  res.send({
    status: 0,
    msg: "获取文章分类列表成功",
    data: results,
  });
};

exports.addArticleCates = async (req, res) => {
  const sql = `select * from ev_article_cate where name=? or alias=?`;
  let results = await sqlPromise(sql, [req.body.name, req.body.alias]);
  if (results.length == 2)
    return res.send({ status: 1, msg: "分类名称与别名被占用，请更换后重试！" });
  if (results.length == 1 && results[0].name == req.body.name)
    return res.send({ status: 1, msg: "分类名称被占用，请更换后重试！" });
  if (results.length == 1 && results[0].alias === req.body.alias)
    return res.send({ status: 1, msg: "分类别名被占用，请更换后重试！" });

  const add_sql = "INSERT INTO ev_article_cate (name,alias) VALUES (?,?)";
  let addRes = await sqlPromise(add_sql, [req.body.name, req.body.alias]);
  console.log(addRes);
  if (addRes.affectedRows !== 1)
    return res.send({ status: 1, msg: "新增文章分类失败！" });
  res.send({
    status: 0,
    msg: "新增文章分类成功！",
  });
};

exports.deleteCateById = async (req, res) => {
  let del_sql = "update ev_article_cate set is_delete=1 where id=?";
  let results = await sqlPromise(del_sql, [req.params.id]);
  if (results.affectedRows !== 1)
    return res.send({ status: 1, msg: "删除文章分类失败！" });
  res.send({
    status: 0,
    msg: "删除文章分类成功！",
  });
};

exports.getArticleById = async (req, res) => {
  const sql = "select * from ev_article_cate where id=?";
  let results = await sqlPromise(sql, [req.params.id]);
  if (results.length == 0)
    return res.send({ status: 1, msg: "获取文章分类列表失败" });
  res.send({
    status: 0,
    msg: "获取文章分类列表成功",
    data: results,
  });
};

exports.updateCateById = async (req, res) => {
  const sql = `select * from ev_article_cate where name=? or alias=?`;
  let results = await sqlPromise(sql, [req.body.name, req.body.alias]);
  if (results.length == 2)
    return res.send({ status: 1, msg: "分类名称与别名被占用，请更换后重试！" });
  if (results.length == 1 && results[0].name == req.body.name)
    return res.send({ status: 1, msg: "分类名称被占用，请更换后重试！" });
  if (results.length == 1 && results[0].alias === req.body.alias)
    return res.send({ status: 1, msg: "分类别名被占用，请更换后重试！" });

  const update_sql = "update ev_article_cate set name=?,alias=? where id=?";
  let updateRes = await sqlPromise(update_sql, [
    req.body.name,
    req.body.alias,
    req.body.id,
  ]);
  if (updateRes.affectedRows !== 1)
    return res.send({ status: 1, msg: "更新文章分类列表失败" });
  res.send({
    status: 0,
    msg: "更新文章分类列表成功",
  });
};
